const storage = {

  prefix: '',

  load(key, defaultValue = undefined, json = true, prefix = true) {
    if (!key) {
      console.warn('storage: you must specify a key')
    } else {
      let result = localStorage.getItem(prefix ? this.prefix + key : key)
      result = result || defaultValue
      if (result && json) {
        let jsonResult = {}
        try {
          jsonResult = JSON.parse(result)
        } catch (e) {
          if (e.name == 'SyntaxError') {
            console.warn('storage: the result can not trans to json object')
          }
        }
        return jsonResult
      }
      return result
    }
  },

  save(key, value, replace = true, prefix = true) {

    if (!key) {
      console.warn('storage: you must specify a key')
      return
    } 

    if (value && typeof value == 'object') {
      value = JSON.stringify(value)
    }

    if (!replace) {
      let isExist = this.load(key)
      if (isExist) return value
    }

    localStorage.setItem(prefix ? this.prefix + key : key, value)
    return value
  }

}

export default storage